<template>
  <div id="app">
    <!-- Header -->
    <header class="header can-sticky">
      <el-row type="flex" justify="space-between" align="middle" class="container">
        <el-col :span="4">
          <div class="logo">
            <a href="/home">
              <img src="@/assets/images/logo.png" alt="logo" />
            </a>
          </div>
        </el-col>
        <el-col :span="16">
          <nav class="navigation">
            <ul class="main-menu">
              <li
                v-for="(item, index) in mainMenu"
                :key="index"
                class="menu-item"
                :class="{ 'menu-item-has-children': !!item.children }"
              >
                <a :href="item.href" @click="handleMenuClick(item, $event)">
                  {{ item.title }}
                </a>

                <!-- 二级菜单 -->
                <ul v-if="item.children" class="sub-menu">
                  <li
                    v-for="(child, childIdx) in item.children"
                    :key="childIdx"
                    class="menu-item"
                    :class="{ 'menu-item-has-children': !!child.children }"
                  >
                    <a :href="child.href" @click="handleMenuClick(child, $event)">
                      {{ child.title }}
                    </a>

                    <!-- 三级菜单 -->
                    <ul v-if="child.children" class="sub-menu">
                      <li
                        v-for="(grandChild, gIdx) in child.children"
                        :key="gIdx"
                        class="menu-item"
                      >
                        <a :href="grandChild.href">{{ grandChild.title }}</a>
                      </li>
                    </ul>
                  </li>
                </ul>
              </li>
            </ul>
          </nav>
        </el-col>
<!--        <el-col :span="4" class="text-right">-->
<!--          <a href="/login" class="header_btn thm-btn btn-rounded btn-small">Log In</a>-->
<!--        </el-col>-->
      </el-row>
    </header>

    <!-- Subheader  -->
    <div class="section-bg section-padding subheader">
      <el-container>
        <el-main>
          <div class="container">
            <el-row type="flex" justify="center">
              <el-col :span="24" class="text-center">
                <h1 class="text-white page-title">Services</h1>
              </el-col>
            </el-row>
          </div>
        </el-main>
      </el-container>
    </div>

    <!-- Services -->
    <section class="services-section">
      <div class="container">
        <!-- 顶部导航 -->
        <div class="service-tabs mb-5">
          <el-tabs v-model="activeCategory" @tab-click="handleTabClick">
            <el-tab-pane v-for="category in categories" :key="category.value" :label="category.label" :name="category.value.toString()">
            <span slot="label">
              <i :class="category.icon"></i> {{ category.label }}
            </span>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 子标签导航（仅在“产业互联网+”类别下显示） -->
        <div v-if="activeCategory === '1'" class="sub-service-tabs mb-5">
          <el-tabs v-model="activeSubTag" @tab-click="handleSubTabClick">
            <el-tab-pane v-for="tag in subTags" :key="tag" :label="tag" :name="tag">
              <span slot="label">{{ tag }}</span>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 服务内容区域 -->
        <div class="service-content">
          <el-row :gutter="20">
            <el-col v-for="(service, index) in currentServices" :key="index" :lg="8" :md="12" :sm="24" class="mb-4">
              <el-card shadow="hover" class="service-card">
                <div class="service-image" @click="goToServiceDetails(service.id)">
                  <el-image :src="fixImgUrl(service.coverImage)" fit="cover" class="w-100 h-100">
                    <template #error>
                      <div class="image-slot">
                        <i class="el-icon-picture-outline"></i>
                      </div>
                    </template>
                  </el-image>
                </div>
                <div class="service-info p-3" @click="goToServiceDetails(service.id)">
                  <h5 class="title mb-2">{{ service.title }}</h5>
                  <p class="description text-secondary small mb-3">{{ service.subtitle }}</p>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </section>

  </div>
</template>

<script>
import {listCases,updateCases} from "@/api/achievement/cases";

export default {
  name: "service",
  data() {
    return {
      mainMenu: [
        {
          title: '首页',
          href: '/home'
        },
        {
          title: '关于',
          href: '/about'
        },
        {
          title: '服务',
          href: '/services',
        },
        {
          title: '博客',
          href: '#',
          children: [
            {
              title: '博客网络',
              href: '#',
              children: [
                { title: '全宽', href: '/blog-grid' },
                { title: '左侧边栏', href: '/blog-grid-left' },
                { title: '右侧边栏', href: '/blog-grid-right' }
              ]
            },
          ]
        },
        {
          title: '联系我们',
          href: '/contact'
        }
      ],
      activeCategory: '0', // 默认选中第一个标签页
      activeSubTag: '0', // 当前选中的子标签
      // 服务数据列表
      serviceList: [],
      loading: false,
      error: null,
      categories: [
        { value: '0', label: '电子政务', icon: 'el-icon-s-platform' },
        { value: '1', label: '产业互联网+', icon: 'el-icon-s-grid' },
        { value: '2', label: '教育运营产品', icon: 'el-icon-school' }
      ]
    };
  },
  computed: {
    categorizedServiceList() {
      return this.categories.reduce((acc, category) => {
        acc[category.value] = this.serviceList.filter(service => service.serviceCategory === category.value);
        console.log(`类别 ${category.value} 的服务数量:`, acc[category.value].length); // 添加这行日志
        return acc;
      }, {});
    },
    currentServices() {
      if (this.activeCategory === '1' && this.activeSubTag) {
        // 如果是“产业互联网+”类别且有选中的子标签，则根据子标签过滤
        return this.categorizedServiceList[this.activeCategory].filter(service => {
          const tags = service.tags ? service.tags.split(',') : [];
          return tags.includes(this.activeSubTag);
        });
      } else {
        // 否则返回该类别的所有服务
        return this.categorizedServiceList[this.activeCategory] || [];
      }
    },
    /**
     * 获取“产业互联网+”类别的所有唯一标签
     */
    subTags() {
      if (this.activeCategory === '1') {
        const tagsSet = new Set();
        this.categorizedServiceList['1'].forEach(service => {
          if (service.tags) {
            service.tags.split(',').forEach(tag => tagsSet.add(tag.trim()));
          }
        });
        return Array.from(tagsSet).sort();
      }
      return [];
    }
  },
  watch: {
    /**
     * 监听 activeCategory 的变化
     */
    activeCategory(newVal) {
      if (newVal === '1') { // 如果是“产业互联网+”类别
        this.activeSubTag = this.subTags.length > 0 ? this.subTags[0] : ''; // 默认选中第一个子标签
      } else {
        this.activeSubTag = ''; // 如果不是，则清空子标签的选择
      }
    }
  },
  created() {
    this.fetchServices();
  },
  methods: {
    fixImgUrl(path) {
      if (!path) return '';
      return path.startsWith(process.env.VUE_APP_BASE_API) ? encodeURI(path) : encodeURI(process.env.VUE_APP_BASE_API + path);
    },

    handleMenuClick(item, event) {
      // 如果有子菜单，阻止跳转，用于展开/收起
      if (item.children) {
        event.preventDefault();
        // 可以在这里添加展开/收起逻辑（比如维护一个展开状态数组）
        console.log('Toggle submenu for:', item.title);
      }
      // 否则允许正常跳转
    },

    fetchServices() {
      this.loading = true;
      // 将分页参数和其他可能的查询参数一起发送
      const params = {
        pageSize: 100,
        type: 'service',
        isPublished: 1,
      };
      listCases(params).then(response => {
        console.log('服务列表数据:', response);

        // 直接获取所有 service 数据
        // const allServiceData = response.rows || [];
        this.serviceList  = response.rows || []; // 将获取的数据赋值给 blogList
        console.log('更新后的 serviceList:', this.serviceList);
        this.total = response.total || 0;
        this.loading = false;
      })
      .catch(error => {
        console.error('获取服务列表失败:', error);
        this.loading = false;
      });
    },
    // 点击卡片跳转到详情页
    goToServiceDetails(serviceId) {
      // 点击详情时跳转到服务详情页面，并且对应的阅读量加1
      const service = this.serviceList.find(service => service.id === serviceId);
      if (service) {
        // 更新阅读量
        service.viewCount++;
        // 发送更新请求
        updateCases(service).then(() => {
          console.log(`服务 ${serviceId} 阅读量已 +1`);
        }).catch(err => {
          console.error('更新失败:', err);
        }).finally(() => {
          // 无论成功失败都跳转
          this.$router.push({ path: `/service-details/${serviceId}` });
        });
      } else {
        this.$router.push({ path: `/service-details/${serviceId}` });
      }
    },
    handleTabClick(tab) {
      this.activeCategory = tab.name;
      this.activeSubTag = ''; // 切换主标签时重置子标签
    },
    handleSubTabClick(tab) {
      this.activeSubTag = tab.name;
    }
  }
}
</script>

<style scoped>
/* 全局重置与字体 */
#app {
  font-family: 'Poppins', sans-serif;
  margin: 0;
  padding: 0;
}

/* 容器居中，类似 Bootstrap */
.container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* =============
   Header 样式
============= */
.header {
  background-color: #ffffff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 15px 0;
  position: relative;
  z-index: 1000;
}

.header.can-sticky {
  position: sticky;
  top: 0;
  transition: all 0.3s ease;
}

.logo img {
  height: 50px;
  transition: all 0.3s ease;
}

.logo img:hover {
  opacity: 0.9;
}

/* 导航栏 - 主菜单 */
.navigation {
  display: flex;
  justify-content: center;
}

.main-menu {
  list-style: none;
  margin: 0;
  padding: 0;
  display: flex;
  gap: 30px;
  align-items: center;
}

.main-menu > .menu-item {
  position: relative;
}

.main-menu > .menu-item > a {
  text-decoration: none;
  color: #333;
  font-weight: 500;
  font-size: 16px;
  transition: color 0.3s ease;
  padding: 5px 0;
  display: block;
}

.main-menu > .menu-item > a:hover,
.main-menu > .menu-item > a.active {
  color: #0066ff;
}

/* 二级菜单 */
.sub-menu {
  position: absolute;
  top: 100%;
  left: 0;
  background: #fff;
  min-width: 200px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  opacity: 0;
  visibility: hidden;
  transform: translateY(-10px);
  transition: all 0.3s ease;
  list-style: none;
  margin: 0;
  padding: 10px 0;
  z-index: 1001;
}

.menu-item-has-children:hover > .sub-menu {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.sub-menu .menu-item {
  padding: 0;
}

.sub-menu .menu-item > a {
  color: #555;
  padding: 10px 20px;
  font-size: 15px;
  display: block;
  transition: background 0.3s ease, color 0.3s ease;
}

.sub-menu .menu-item > a:hover {
  background-color: #f5f9ff;
  color: #0066ff;
  padding-left: 24px;
}

/* 三级菜单 */
.sub-menu .sub-menu {
  left: 100%;
  top: 5px;
}

/* 登录按钮 */
.header_btn {
  background-color: #0066ff;
  color: #fff !important;
  padding: 10px 20px;
  text-decoration: none;
  border-radius: 30px;
  font-size: 14px;
  font-weight: 600;
  transition: all 0.3s ease;
  display: inline-block;
  border: none;
  outline: none;
}

.header_btn:hover {
  background-color: #0052cc;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 102, 255, 0.3);
}

/* =============
   Subheader 样式
============= */
.subheader {
  background-image: url('https://images.unsplash.com/photo-1517694712202-14dd9538aa97?ixlib=rb-4.0.3&auto=format&fit=crop&w=1350&q=80');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  padding: 100px 0;
  color: #fff;
  position: relative;
}

.subheader::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6); /* 深色遮罩提升文字可读性 */
  z-index: 1;
}

.subheader .el-main {
  position: relative;
  z-index: 2;
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-title {
  font-size: 3rem;
  font-weight: 700;
  margin: 0;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  letter-spacing: -0.5px;
}

.text-white {
  color: #ffffff;
}

.text-center {
  text-align: center;
}

/* =============
   响应式设计
============= */
@media (max-width: 992px) {
  .main-menu {
    gap: 20px;
  }

  .page-title {
    font-size: 2.5rem;
  }
}

@media (max-width: 768px) {
  .header {
    padding: 12px 0;
  }

  .logo img {
    height: 40px;
  }

  .main-menu {
    gap: 15px;
    flex-wrap: wrap;
    justify-content: center;
  }

  .main-menu > .menu-item {
    font-size: 14px;
  }

  .sub-menu {
    min-width: 180px;
  }

  .sub-menu .menu-item > a {
    padding: 8px 16px;
    font-size: 14px;
  }

  .page-title {
    font-size: 2rem;
  }

  .container {
    padding: 0 15px;
  }
}

@media (max-width: 576px) {
  .main-menu {
    gap: 10px;
    font-size: 14px;
  }

  .header_btn {
    padding: 8px 16px;
    font-size: 13px;
  }

  .page-title {
    font-size: 1.8rem;
  }
}
/* 保持与原有样式一致或自定义 */
.section-padding {
  padding: 60px 0;
}

.title {
  font-size: 1.1rem;
  color: #333;
  font-weight: 500;
}

/* 图片占位符样式 */
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.services-section {
  padding: 60px 0;
}

.service-card {
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
}

.service-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.service-image {
  height: 200px;
  overflow: hidden;
}

.service-info {
  text-align: center;
}

.title {
  font-size: 1.1rem;
  color: #333;
  font-weight: 500;
}

.description {
  color: #666;
  line-height: 1.5;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.services-section {
  padding: 60px 0;
}

.service-tabs,
.sub-service-tabs {
  display: flex;
  justify-content: center;
  align-items: center;
}

.service-tabs ::v-deep .el-tabs__item,
.sub-service-tabs ::v-deep .el-tabs__item {
  font-size: 24px !important;
  font-weight: bold;
}

.service-tabs ::v-deep .el-icon-s-platform,
.service-tabs ::v-deep .el-icon-s-grid,
.service-tabs ::v-deep .el-icon-school {
  font-size: 24px !important;
  margin-right: 8px;
}
</style>
